package com.sys.util;

import com.sys.handle.OnTimeHandler;

import java.util.Calendar;
import java.util.Timer;
import java.util.Vector;

/**
 * create by fbdh
 */
@SuppressWarnings("unused")
public class TimerUtils {
    //timerVector
    private static Vector<Timer> timerVector = new Vector<>();

    /**
     * @param handler  方法
     * @param milliSec シャルディレイmilliSec執行方法
     * @return timer
     */
    public static Timer setTimeout(OnTimeHandler handler, long milliSec) {
        Timer timer = new Timer(true);
        MyTimerTask task = new MyTimerTask();
        task.setHandler(handler);
        task.setTimer(timer);
        task.setInterval(false);
        timer.schedule(task, milliSec, 999999);
        timerVector.add(timer);
        return timer;
    }

    /**
     * @param handler  方法
     * @param milliSec シャルディレイmilliSec執行一度
     * @return timer
     */
    public static Timer setInterval(OnTimeHandler handler, int milliSec) {
        Timer timer = new Timer(true);
        Calendar twentyOne = Calendar.getInstance();
        twentyOne.set(Calendar.DAY_OF_YEAR, twentyOne.get(Calendar.HOUR_OF_DAY));
        twentyOne.set(Calendar.MINUTE, twentyOne.get(Calendar.MINUTE));
        twentyOne.set(Calendar.SECOND, twentyOne.get(Calendar.SECOND));
        twentyOne.add(Calendar.MILLISECOND, milliSec);
        MyTimerTask task = new MyTimerTask();
        task.setHandler(handler);
        task.setTimer(timer);
        task.setInterval(true);
        timer.schedule(task, twentyOne.getTime(), milliSec);
        timerVector.add(timer);
        return timer;
    }

    /**
     * すべてtimerクリア
     */
    public static void clearAllTimer() {
        for (Timer t : timerVector) {
            if (t != null) {
                t.cancel();
            }
        }
    }

    /**
     * 安全の削除timer
     *
     * @param timer timer
     */
    public static void clearTimer(Timer timer) {
        if (timer == null) return;

        timerVector.remove(timer);
        timer.cancel();
    }
}